package com.mio.web.common;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.durcframework.core.SpringContext;
import org.springframework.stereotype.Component;

import com.mio.web.entity.log.SysLog;
import com.mio.web.entity.user.User;
import com.mio.web.service.log.SysLogService;
import com.mio.web.service.user.UserService;

@Component
public class SimpleCORSFilter implements Filter {
	// 30秒验证时间
	long between = 1 * 1000 * 30;

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers",
				"X-Requested-With,content-type, Authorization,Origin,Accept");

		SysLogService sysLogService = (SysLogService) SpringContext.getBean(SysLogService.class);

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		SysLog sysLog = new SysLog();
		Date now = new Date();
		// 有人访问过首页则代表访问人数+1
		//if (request.getRequestURI().equals("/")) {
			// 查找该ip地址今日是否已访问过
			boolean flag = sysLogService.isExsist(request.getRemoteAddr(), simpleDateFormat.format(now));
			if (!flag) {
				sysLog.setRequestURL("" + request.getRequestURI());
				sysLog.setQueryString(request.getQueryString());
				sysLog.setIp(request.getRemoteAddr());
				sysLog.setHeader(request.getHeader("referer"));
				sysLog.setTableName("sysLog");
				sysLogService.saveLog(sysLog);
				
			}
			
			//获取访问人数
			request.getSession().setAttribute("visitNumber", sysLogService.getVisitNumber());
		//}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) {
	}

	public void destroy() {
	}
}
